package com.gmall.rabbitmq.producer.controller;

import com.gmall.rabbitmq.config.HeaderExchange_Queue_Config;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/headerEx")
public class HeaderExController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    private int count =0;

    /**
     *
     * @param map  {"inform1":"email","inform2":"sms"}
     * @return
     */
    @PostMapping("/produce")
    public String produce(@RequestBody Map<String,String> map){
        /**
         * String exchange, 交换机
         * String routingKey, 路由key
         * Object message, 消息
         * MessagePostProcessor messagePostProcessor, 设置消息唯一ID和持久化
         * @Nullable CorrelationData correlationData 用户生产端Confirm
         */
        String body = "hello,world" + count++;

//        MessageProperties properties = new MessageProperties();
//        properties.setMessageId("123456");
//        map.forEach((key,value)->{
//            properties.setHeader(key,value);
//        });
//        Message messageRaw = new Message(body.getBytes(),properties);
//        rabbitTemplate.send(messageRaw);

        rabbitTemplate.convertAndSend(
                HeaderExchange_Queue_Config.HEADER_EXCHANGE,
                "",
                body,
                (message)->{
                    message.getMessageProperties().setMessageId("123456");

//                    Set<String> set = map.keySet();
//                    for(String key:set){
//                        String value = map.get(key);
//
//                        message.getMessageProperties().setHeader(key,value);
//                    }
//
//                    //Collection<String> values = map.values();
//
//                    Set<Map.Entry<String, String>> entries = map.entrySet();
//                    Iterator<Map.Entry<String, String>> iterator = entries.iterator();
//                    while (iterator.hasNext()){
//                        Map.Entry<String, String> entry = iterator.next();
//                        entry.getKey();
//                        entry.getValue();
//                    }

                    map.forEach((key,value)->{
                        message.getMessageProperties().setHeader(key,value);
                    });
                    return  message;
                });

        return "success";
    }


}
